package com.cnpc.fyutils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

/**
 * EditText输入框的工具类����
 *
 * @author Administrator
 */
public class EditText_util {

    // 输入表情前的光标位置
    private static int cursorPos;
    // 输入表情前EditText中的文本
    private static String inputAfterText;
    // 是否重置了EditText的内容
    private static boolean resetText;

    /**
     * 设置输入框只能输入数字和大小写字母
     */
    public static void setedittext_type_numberletters(EditText edittext) {
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable edt) {
                try {
                    String temp = edt.toString();
                    String tem = temp.substring(temp.length() - 1, temp.length());
                    char[] temC = tem.toCharArray();
                    int mid = temC[0];
//					if (mid >= 48 && mid <= 57) {// 数字
//						return;
//					}
//					if (mid >= 65 && mid <= 90) {// 大写字母
//						return;
//					}
//					if (mid > 97 && mid <= 122) {// 小写字母
//						return;
//					}
                    if (regular_judge(temp)) {
                        return;
                    }
                    edt.delete(temp.length() - 1, temp.length());
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        });
    }

    /**
     * 判断字符串是否符合正则表达式
     */
    public static boolean regular_judge(String str) {
        String pat = "^[a-zA-Z0-9]{0,20}+$";
        Pattern pattern = Pattern.compile(pat);
        Matcher matcher = pattern.matcher(str);
        boolean b = matcher.matches();
        return b;

    }

    /**
     * 限制Eidttext输入特殊字符的方法
     */
    public static void seteidttext_astrictcharacter(final EditText edittext) {

        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    cursorPos = edittext.getSelectionEnd();
                    // 这里用s.toString()而不直接用s是因为如果用s，
                    // 那么，inputAfterText和s在内存中指向的是同一个地址，s改变了，
                    // inputAfterText也就改变了，那么表情过滤就失败了
                    inputAfterText = s.toString();
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!resetText) {
                    if (count >= 1) {// 表情符号的字符长度最小为2
                        CharSequence input = "";
                        try {
                            input = s.subSequence(cursorPos, cursorPos + count);
                        } catch (IndexOutOfBoundsException e) {
                            input = "";
                            resetText = false;
                        }

                        if (containsEmoji(input.toString())) {
                            resetText = true;
                            // 是表情符号就将文本还原为输入表情符号之前的内容
                            edittext.setText(inputAfterText);
                            CharSequence text = edittext.getText();
                            if (text instanceof Spannable) {
                                Spannable spanText = (Spannable) text;
                                Selection.setSelection(spanText, text.length());
                            }
                        }
                    }
                } else {
                    resetText = false;
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    /**
     * 检测是否有emoji表情
     *
     * @param source
     * @return
     */
    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 限制输入框字数并显示字数的方法
     *
     * @param edt_message EditText控件
     * @param tv_number   显示字数的textview控件
     * @param num         最大字数
     */
    public static void setandshowe_ditnumber(final EditText edt_message, final TextView tv_number, final int num) {
        edt_message.addTextChangedListener(new TextWatcher() {
            private CharSequence temp;
            private int selectionStart;
            private int selectionEnd;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                temp = s;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                int number = s.length();
                tv_number.setText(number + "/" + num);
                selectionStart = edt_message.getSelectionStart();
                selectionEnd = edt_message.getSelectionEnd();
                if (temp.length() > num) {
                    s.delete(selectionStart - 1, selectionEnd);
                    int tempSelection = selectionEnd;
                    edt_message.setText(s);
                    edt_message.setSelection(tempSelection);// 设置光标在最后

                }
            }
        });
    }

    /**
     * 判断是否是Emoji
     *
     * @param codePoint 比较的单个字符
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint) {
        if (codePoint == 9786) {
            return false;
        }
        return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }
    /**
     * 将软键盘隐藏的方法
     */
    public static void hideKeyboard(Activity activity) {


        try {
            ((InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
